package com.zcsy.commons.upload;

import java.io.File;

import org.springframework.beans.factory.annotation.Autowired;

import com.zcsy.commons.upload.FileUploadUtil.UploadFileItem;

/**
 * 上传文件操作.<br>
 * @author tanghan   barbadosliy@163.com
 * @version 2015年6月7日
 * @see FileHelper
 * @since
 */
public class FileHelper implements IFileHelper {

	private IFileResource fileResource;

	private IFileUrlHelper fileUrlHelper;

	/**
	 * 设置fileReource.
	 * 
	 * @param newFileResource
	 *            the fileResource to set
	 */
	@Autowired
	public void setFileResource(IFileResource newFileResource) {
		this.fileResource = newFileResource;
	}

	/**
	 * 设置fileUrlHelper.
	 * 
	 * @param newFileUrlHelper
	 *            the fileUrlHelper to set
	 */
	@Autowired
	public void setFileUrlHelper(IFileUrlHelper newFileUrlHelper) {
		this.fileUrlHelper = newFileUrlHelper;
	}

	/**
	 * {@inheritDoc}
	 * 
	 * @see IFileHelper#saveTempFile(String, String, String)
	 */
	public String saveTempFile(String token, String path, String fileId) {
		final UploadFileItem fileInfo = FileUploadUtil.getUploadFile(token, path, fileId);
		if (fileInfo == null) {
			return null;
		}
		final File internalFile = fileInfo.getInternalFile();

		final String id = fileResource.save(internalFile);
		final String url = fileUrlHelper.getUrl(id);
		return url;
	}

	/**
	 * {@inheritDoc}
	 * 
	 * @see IFileHelper#deleteByUrl(String)
	 */
	public boolean deleteByUrl(String url) {
		final String id = fileUrlHelper.getIdentity(url);
		return fileResource.del(id);
	}

}
